package com.ruoyi.web.controller.publish;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.publish.domain.IdAcceptRegister;
import com.ruoyi.publish.domain.IdIdentsample;
import com.ruoyi.publish.domain.IdLaw;
import com.ruoyi.publish.service.IIdAcceptRegisterService;
import com.ruoyi.publish.service.IIdIdentsampleService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.publish.domain.IdReport;
import com.ruoyi.publish.service.IIdReportService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 鉴定报告Controller
 *
 * @author confusefox
 * @date 2020-11-17
 */
@Controller
@RequestMapping("/publish/report")
public class IdReportController extends BaseController {
    private String prefix = "publish/report";

    @Autowired
    private IIdReportService idReportService;

    @Autowired
    private IIdAcceptRegisterService idAcceptRegisterService;

    @Autowired
    private IIdIdentsampleService idIdentsampleService;

    //    @RequiresPermissions("publish:report:view")
    //    @RequiresPermissions("publish:report:view")
    @GetMapping()
    public String report() {
        return prefix + "/report";
    }

    /**
     * 查询鉴定报告列表
     */
//    @RequiresPermissions("publish:report:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(IdReport idReport) {
        startPage();
        List<IdReport> list = idReportService.selectIdReportList(idReport);
        return getDataTable(list);
    }

    /**
     * 导出鉴定报告列表
     */
//    @RequiresPermissions("publish:report:export")
    @Log(title = "鉴定报告", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(IdReport idReport) {
        List<IdReport> list = null;
        if (StringUtils.isNotEmpty(idReport.getExportIds())) {
            list = idReportService.selectRecordByIds(idReport.getExportIds().split(","));
        } else {
            list = idReportService.selectIdReportList(idReport);
        }
        ExcelUtil<IdReport> util = new ExcelUtil<IdReport>(IdReport.class);
        return util.exportExcel(list, "report");
    }

    /**
     * 新增鉴定报告
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存鉴定报告
     */
//    @RequiresPermissions("publish:report:add")
    @Log(title = "鉴定报告", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(IdReport idReport,String copyrightRecordEx) {
        // 设置创建人
        idReport.setCreateBy(ShiroUtils.getSysUser().getUserId().toString());
        idReport.setTakeover(ShiroUtils.getSysUser().getUserName());
        idReport.setCopyrightRecordEx(copyrightRecordEx);

        //获取案件受理时间
        IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(idReport.getRegisterId());
        idReport.setAcceptTime(idAcceptRegister.getAcceptDate());
        return toAjax(idReportService.insertIdReport(idReport));
    }

    /**
     * 修改鉴定报告
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        IdReport idReport = idReportService.selectIdReportById(id);
        mmap.put("idReport", idReport);
        return prefix + "/edit";
    }

    /**
     * 查看鉴定报告
     */
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap) {
        IdReport idReport = idReportService.selectIdReportById(id);
        mmap.put("idReport", idReport);
        mmap.put("userid", ShiroUtils.getSysUser().getUserId());
        return prefix + "/detail";
    }

    /**
     * 修改保存鉴定报告
     */
//    @RequiresPermissions("publish:report:edit")
    @Log(title = "鉴定报告", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(IdReport idReport) {
        idReport.setUpdateBy(ShiroUtils.getSysUser().getUserId().toString());
        idReportService.IdReportRefreshByRecordId(idReport.getId());//修改鉴定报告之后，清除之前对应word
        return toAjax(idReportService.updateIdReport(idReport));
    }

    /**
     * 删除鉴定报告
     */
//    @RequiresPermissions("publish:report:remove")
    @Log(title = "鉴定报告", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(idReportService.deleteIdReportByIds(ids));
    }

    /**
     * 是否启用状态修改
     */
    @Log(title = "鉴定报告修改启用状态", businessType = BusinessType.UPDATE)
//    @RequiresPermissions("publish:identsample:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(IdReport idReport) {
        return toAjax(idReportService.changeStatus(idReport));
    }

    /**
     * 是否启用状态修改
     */
    @Log(title = "进入相应鉴定报告", businessType = BusinessType.OTHER)
//    @RequiresPermissions("publish:identsample:edit")
    @GetMapping("/apprReport/{id}")
    public String report(@PathVariable("id") Long id, ModelMap mmap) {

        IdIdentsample idSample = idIdentsampleService.selectIdIdentsampleById(id);
        if (idSample != null && StringUtils.isNotEmpty(idSample.getBy1())) {
            IdReport idReport = idReportService.selectIdReportById(Long.parseLong(idSample.getBy1()));
            if (idReport != null) {
                IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(idReport.getRegisterId());
                mmap.put("idReport", idReport);
                mmap.put("idAcceptRegister", idAcceptRegister);
                System.out.println(idAcceptRegister);
            }
        } else {
            IdReport idReport = new IdReport();
            idReport.setAppraCon("待鉴定");
            IdAcceptRegister idAcceptRegister = idAcceptRegisterService.selectIdAcceptRegisterById(idSample.getRegisterId());
            mmap.put("idReport", idReport);
            mmap.put("idAcceptRegister", idAcceptRegister);

        }

        return prefix + "/apprReport";
    }


    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {

        ExcelUtil<IdReport> util = new ExcelUtil<IdReport>(IdReport.class);
        List<IdReport> list = new ArrayList<>();
        IdReport idReport = new IdReport();
        //鉴定结论
        idReport.setAppraCon("非法出版物");
        //简要案情
        idReport.setBriefCase("（示范，本行勿删）");
        //鉴定内容
        idReport.setIdentiContent("内容详情（示范）");
//        //样本版权记录
//        idReport.setCopyrightRecord("样本版权记录(示范)");
        //鉴定情况
        idReport.setIdentiSituation("情况详情(示范)");
        list.add(idReport);
        return util.importDataTemplateExcel(list, "鉴定报告数据");
    }

    @Log(title = "鉴定报告excel导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport, String year) throws Exception {
        byte[] bytes = file.getBytes();
        InputStream in = new ByteArrayInputStream(bytes);

        ExcelUtil<IdReport> util = new ExcelUtil<IdReport>(IdReport.class);
        List<IdReport> userList = util.importExcel(in);

        String operName = ShiroUtils.getSysUser().getUserName();
        String operId = ShiroUtils.getUserId().toString();
        String message = idReportService.importIdReport(userList, updateSupport, operId, operName, year);
        return AjaxResult.success(message);
//        return null;
    }


    /**
     * 下载本地文件
     */
    @RequestMapping("/doLoad")
    public void doLoad(HttpServletRequest request, HttpServletResponse response) {
        String filename = "鉴定报告数据";

        try {
            // 清空输出流
            response.reset();
            String resultFileName = filename + ".xlsx";
            resultFileName = URLEncoder.encode(resultFileName, "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + resultFileName);// 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型
            //输入流：文件路径
            DataInputStream in = new DataInputStream(
                    new FileInputStream(new File("/RuoYi/ruoyi-admin/src/main/resources/static/excelTemplate/鉴定报告数据.xlsx")));
            //输出流
            OutputStream out = response.getOutputStream();
            //输出文件
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            // 清空输出流
            response.reset();
        }
    }

    /**
     * 一键更新
     */
//    @RequiresPermissions("publish:register:edit")
    @Log(title = "一键更新word文档鉴定报告", businessType = BusinessType.UPDATE)
    @PostMapping("/refresh/{id}")
    @ResponseBody
    public AjaxResult refresh(@PathVariable("id") Long id, ModelMap mmap) {

        return toAjax(idReportService.IdReportRefreshByRecordId(id));
    }

    /**
     * 审核报告审核界面
     */
    @GetMapping("/audit")
    public String audit() {
        return prefix + "/audit";
    }

    /**
     * 审批页面信息
     *
     * @return
     */
    @GetMapping("/openApprovalWindow")
    public String openApprovalWindow() {
        return prefix + "/approvalwin";
    }
}
